<template>
  <el-form
    ref="formRef"
    label-width="auto"
    :label-position="props.isEdit ? 'top' : 'right'"
    :hide-required-asterisk="!props.isEdit"
    :model="formValue"
    :rules="formRules"
  >
    <el-row :gutter="40">
      <el-col :span="8">
        <el-form-item prop="goods_certify_no" :label="$t('goods_document.goods_certify_no')">
          <el-input v-if="props.isEdit" v-model="formValue.goods_certify_no" v-trim class="qf_input" />
          <span v-else>{{ formValue.goods_certify_no }}</span>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item prop="start_date" :label="$t('goods_document.period_date')">
          <el-date-picker
            v-if="props.isEdit"
            v-model="validPeriod"
            class="qf_date"
            type="daterange"
            :range-separator="$t('merak.rangto')"
            :format="format"
            :value-format="format"
          />
          <span v-else>{{ formValue.start_date }} {{ $t("merak.rangto") }} {{ formValue.end_date }}</span>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item prop="goods_certify_type" :label="$t('goods_document.goods_certify_type')">
          <el-select v-if="props.isEdit" v-model="formValue.goods_certify_type" class="qf_select">
            <el-option v-for="option in state.documentType" :value="option.value" :label="option.label" />
          </el-select>
          <span v-else>{{ state.documentType.find(option => option.value === formValue?.goods_certify_type)?.label }}</span>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item prop="apply_name_factory" :label="$t('goods_document.apply_name_factory')">
          <el-select
            v-if="props.isEdit"
            v-model="formValue.apply_name_factory"
            class="qf_select"
            filterable
            remote
            remote-show-suffix
            :placeholder="$t('goods_document.search_factory_name')"
            :remote-method="handleRemote"
          >
            <el-option v-for="item in state.applySearchResult" :value="item.value" :label="item.label" />
          </el-select>
          <span v-else>{{ state.applyType.find(option => option.value === formValue?.apply_name_factory)?.label }}</span>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item prop="adult_child" :label="$t('goods_document.adult_child')">
          <el-radio-group v-if="props.isEdit" v-model="formValue.adult_child">
            <el-radio v-for="option in state.ageType" :value="option.value" :label="option.label" />
          </el-radio-group>
          <span v-else>{{ state.ageType.find(option => option.value === formValue?.adult_child)?.label }}</span>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item prop="type_id" :label="$t('goods_document.type_id')">
          <el-select v-if="props.isEdit" v-model="formValue.type_id" class="qf_select">
            <el-option v-for="option in state.goodType" :value="option.value" :label="option.label" />
          </el-select>
          <span v-else>{{ state.goodType.find(option => option.value === formValue?.type_id)?.label }}</span>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item prop="other_brands" :label="$t('goods_document.brand_title')">
          <el-input
            v-if="props.isEdit"
            v-model="formValue.other_brands"
            v-trim
            type="textarea"
            :placeholder="$t('goods_document.textarea_placeholder')"
            :autosize="{ minRows: 2, maxRows: 4 }"
          />
          <span v-else>
            <el-popover placement="top-start" :width="500" trigger="click">
              <template #reference>
                <span class="brands">
                  {{ formValue.other_brands }}
                </span>
              </template>
              <div class="brands_popover">
                {{ formValue.other_brands }}
              </div>
            </el-popover>
          </span>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item prop="hs_codes" :label="$t('goods_document.hs_codes')">
          <el-input
            v-if="props.isEdit"
            v-model="formValue.hs_codes"
            v-trim
            type="textarea"
            :placeholder="$t('goods_document.textarea_placeholder')"
            :autosize="{ minRows: 2, maxRows: 4 }"
          />
          <span v-else>{{ formValue.hs_codes }}</span>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item prop="product_description" :label="$t('goods_document.product_description')">
          <el-input
            v-if="props.isEdit"
            v-model="formValue.product_description"
            v-trim
            type="textarea"
            :placeholder="$t('goods_document.textarea_placeholder')"
            :autosize="{ minRows: 2, maxRows: 4 }"
          />
          <span v-else>{{ formValue.product_description }}</span>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>

<script setup lang="ts">
import { getCurrentInstance, ref, reactive, computed, onMounted } from "vue";

import { useRoute } from "vue-router";

import useDateFormat from "@/hooks/useDateFormat";

import {
  FormRules,
  ElMessage,
  ElForm,
  ElFormItem,
  ElRow,
  ElCol,
  ElInput,
  ElDatePicker,
  ElSelect,
  ElOption,
  ElRadioGroup,
  ElRadio
} from "element-plus";

import { ResultEnum } from "@/enums/httpEnum";
import { OptionType, getDetail, saveBase } from "@/api/modules/goodsArchive/document";

import { confirmWarningMsg } from "@/utils/messageUtils";
import { getCertifyApi, getProductInfoApi } from "@/api/modules/goodsArchive/list/detail";
const props = defineProps<{
  queueId?: string;
  isEdit: boolean;
  productId?: string | number;
}>();

const currentInstance = getCurrentInstance();

const route = useRoute();

const { format } = useDateFormat();

const formRef = ref<InstanceType<typeof ElForm>>();

const state = reactive<{
  loading: boolean;
  dropdownList: object;
  copy: Record<string, any>;
  documentType: OptionType[];
  goodType: OptionType[];
  applyType: OptionType[];
  applySearchResult: OptionType[];
  ageType: OptionType[];
  title: string;
}>({
  loading: false,
  dropdownList: {},
  copy: {},
  documentType: [],
  goodType: [],
  applyType: [],
  applySearchResult: [],
  ageType: [],
  title: ""
});

const formValue = reactive<Record<string, any>>({});

const formRules = reactive<FormRules>({
  goods_certify_no: [{ required: true, message: currentInstance?.proxy?.$t("goods_document.goods_certify_no_valid") }],
  start_date: [{ required: true, message: currentInstance?.proxy?.$t("goods_document.period_date_valid") }],
  apply_name_factory: [{ required: true, message: currentInstance?.proxy?.$t("goods_document.apply_name_factory_valid") }],
  other_brands: [{ required: true, message: currentInstance?.proxy?.$t("goods_document.other_brands_valid") }]
});

const validPeriod = computed({
  get: () => {
    const { start_date, end_date } = formValue;
    if (!!start_date && !!end_date) {
      return [start_date, end_date] as [string, string];
    }
    return;
  },
  set: value => {
    const [start_date, end_date] = value ?? [];
    formValue.start_date = start_date;
    formValue.end_date = end_date;
  }
});

// 申请公司检索
const handleRemote = (query: string) => {
  state.applySearchResult = !!query
    ? state.applyType.filter(option => option.label.toLowerCase().includes(query.toLowerCase()))
    : !!formValue.apply_name_factory
      ? state.applyType.filter(option => option.value === formValue.apply_name_factory)
      : [];
};

const getCertify = (certifyObj, type) => {
  state.loading = !!props.queueId ? false : true;
  getCertifyApi({ product_id: props.productId, goods_certify_id: certifyObj?.goods_certify_id }, props.queueId).then(
    ({ code, data }) => {
      if (code == ResultEnum.SUCCESS) {
        const { goods_certify_type, apply_company, adult_child, type_id } = data.filter;
        if (data.certifyList) {
          state.documentType = goods_certify_type;
          state.applyType = apply_company;
          state.ageType = adult_child;
          state.goodType = type_id;

          if (!!data.goods_certify.apply_name_factory) {
            state.applySearchResult = apply_company.filter(option => option.value === data.goods_certify.apply_name_factory);
          }
          if (type == "init") {
            state.dropdownList = data.certifyList;
          }
        }

        Object.assign(formValue, { ...data.goods_certify });
      }
    }
  );
};

onMounted(() => {
  // getCertify({}, "init");
});

defineExpose({
  getCertify,
  dropdownList: computed(() => state.dropdownList)
});
</script>

<style scoped lang="scss">
:deep(.el-form-item__label-wrap) {
  margin-right: 30px;
}
.el-form-item__content > span {
  word-break: break-word;
}

.brands {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 8;
  overflow: hidden;
  text-overflow: ellipsis;
}
.brands_popover {
  word-break: break-all;
  height: 250px;
  overflow-y: auto;
}
</style>
